package cn.itsource.zcn.basic.controller;

import cn.itsource.zcn.basic.service.ISendCoderService;
import cn.itsource.zcn.user.domain.User;
import cn.itsource.zcn.user.service.IUserService;
import cn.itsource.zcn.utils.AjaxResult;
import cn.itsource.zcn.utils.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/code")
public class SendCoderController {

    @Autowired
    private ISendCoderService sendCoderService;

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendCode")
    public AjaxResult sendCode(@RequestBody Map<String,String> map){
        // 获取手机号，如果已经注册，就报错
        String phone = map.get("phone");
        String codeType = map.get("codeType");

        String randomString = StrUtils.getRandomString(6)+":"+System.currentTimeMillis();

        User user = userService.queryByPhone(phone);
        //如果验证码是注册类型，就会弹出手机号已注册
        if(codeType.equals("REGISTER_CODE")){
            if(user!=null){
                return AjaxResult.me().setMessage("手机号已注册").setSuccess(false);
            }
        }
        // 防止用户在一分钟之内多次发送验证码
        String codeAndTime = (String)redisTemplate.opsForValue().get(phone);
        if(codeAndTime!=null) {
            Long time = Long.valueOf(codeAndTime.split(":")[1]);
            if ((System.currentTimeMillis() - time) < 60 * 1000) {
                try {
                    throw new RuntimeException("操作频繁！");
                } catch (Exception e) {
                    e.printStackTrace();
                    return AjaxResult.me().setMessage(e.getMessage()).setSuccess(false);
                }
            }
            // 短信在1分钟之内由于第三方原因，并未发送成功！下次发送和之前保持一致
            randomString = (String) redisTemplate.opsForValue().get(phone);
        }
        System.out.println(randomString);
        sendCoderService.send(phone,randomString);

//        System.out.println(redisTemplate.opsForValue().get(phone));
        return AjaxResult.me();
    }
}
